package com.hhxy.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author ghp
 * @date 2023/1/4
 * @title 全局异常处理器
 * @description
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 进行异常处理
     */
    @ExceptionHandler(Exception.class)
    public R<String> exceptionHandler(Exception e) {
        log.error(e.getMessage());
        // 给出更加详细的提示信息
        if (e.getMessage().contains("Duplicate entry")) {
            String msg = e.getMessage();
            int index = msg.indexOf("Duplicate entry");
            msg = msg.substring(index);
            String[] split = msg.split(" ");
            msg = split[2] + "已存在";
            return R.error(msg);
        }

        return R.error("服务器异常，请重新尝试");
    }
}
